package com.website.dayouziblog.intercepter;

import com.website.dayouziblog.exception.BaseErrorEnum;
import com.website.dayouziblog.exception.BaseException;
import com.website.dayouziblog.utils.RedisUtil;
import com.website.dayouziblog.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginIntercepter implements HandlerInterceptor {

    //日志
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginIntercepter.class);

    @Autowired
    private RedisUtil redisUtil;

    @Value("${key.user_token}")
    private String user_token;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //跨域请求会首先发一个options请求，直接返回正常状态并通过拦截器
        if (request.getMethod().equals("options")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        response.setCharacterEncoding("utf-8");
        //校验token
        String token = request.getHeader("Authorization");

        //如果token不为null
        if (null != token) {
            //使用TokenUtils解析token
            String userAccount = TokenUtils.verify(token);
            if (!StringUtils.isEmpty(userAccount)){
                //使用redis校验token
                String key = user_token + userAccount;
                if (redisUtil.get(key).equals(token)){
                    LOGGER.info("token校验成功，通过拦截器");
                    return true;
                }
            }
        }

        //如果token为null
        response.setContentType("application/json; charset=utf-8");
        try {
            JSONObject json = new JSONObject();
            json.put("msg", "token is null");
            json.put("code", "500");
            response.getWriter().append(json.toString());
//            response.sendRedirect(request.getContextPath() + "/login.html");
        } catch (Exception e) {
            LOGGER.debug(e.getMessage());
            e.printStackTrace();
            return false;
        }
        return false;
    }
}
